Express Web App 靜態、動態路由


Posted by mijouhsieh on 2021-12-28

使用Express framework

在res.send(),使用反引號把內容包起來,因為內容可能會有單引、雙引和斷行。

nodemon 工具

nodemon js檔 啟動Node.js伺服器

設定路由(靜態路由)

  • 路由 routing: 當瀏覽器發出請求時,一個網路應用程式如何回應。請求包含一個網址和特定HTTP方法(GET瀏覽、POST新增、PATCH修改、PUT修改新增、DELETE刪除等等)。
  • 路由設定: 使用者輸入網址後,伺服器會回應什麼內容

     app.get('/hello',(req,res) => {
         res.send('have a nice day')
     )
    

    第一個參數放路由, / 稱作 "根目錄"。
    第二個參數是個函式,回應的內容。
    Q: HTTP Request可分成GET和POST兩種方法,他們傳輸資料的方法有什麼不同?

動態路由 params

動態路由: 頁面顯示的內容,可根據輸入的路由而改變。
使用Express框架,取得網址內的資訊,在路由上給一個變數(params)讓server知道user在網址列輸入了什麼。

    app.get('/hello/:name',(req,res) => {
        res.send('hello Mi, have a nice day!')
    )

/hello/ => 路由設定不能改變的網址。
:name => params變數,任何合法字串。

<取得動態路由中params的內容>透過req物件裡的params,就可以取得動態路由中user輸入的內容。

    app.get('/hello/:name',(req,res) => {
        console.log('req.params.name', req.params.name)
        res.send('hello Mi, have a nice day!')
    )

console.log('req.params.name', req.params.name)terminal就會呈現動態路由中params的內容。

<將params的內容呈現在瀏覽器>

    app.get('/hello/:name',(req,res) => {
        console.log('req.params.name', req.params.name)
        res.send(`hello ${req.params.name}, have a nice day!`)
    )

req物件裡的params物件裡的名為name變數(物件中的key),對應到的value就是在url中的params變數。
debug 注意: req不要寫成request !!!


#Express #params #Express routing







Related Posts

如何使用 Heroku 部屬一個 Web App 網頁應用程式

如何使用 Heroku 部屬一個 Web App 網頁應用程式

宜蘭遊 1th  feat.台北

宜蘭遊 1th feat.台北

babel, gulp, webpack 簡介

babel, gulp, webpack 簡介


Comments